package com.example;

import com.alibaba.fastjson.JSONObject;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.List;

public class GetReferenceExample {
    static EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
    public static void main(String[] args) {
        persistEntity(emf);
        updateByReference(emf);
        updateByEntity(emf);
        findAllEmployees(emf);
        emf.close();
    }
    private static void updateByReference(EntityManagerFactory emf){
        EntityManager em = emf.createEntityManager();
        Employee employee = em.getReference(Employee.class,1);
        em.getTransaction().begin();
        employee.setDepartment("IT");
        em.getTransaction().commit();
        em.close();
    }
    private static void updateByEntity(EntityManagerFactory emf){
        EntityManager em = emf.createEntityManager();
        Employee employee = em.find(Employee.class,1);
        em.getTransaction().begin();
        employee.setName("Diana");
        em.getTransaction().commit();
        em.close();
    }
    private static void findAllEmployees(EntityManagerFactory emf){
        EntityManager em = emf.createEntityManager();
        Query query = em.createQuery("select e from Employee e");
        List<Employee> employees = query.getResultList();
        for (Employee employee : employees) {
            System.err.println(JSONObject.toJSONString(employee,false));
        }
    }
    private static Employee persistEntity(EntityManagerFactory emf){
        Employee employee = new Employee("Sara Dorsey","Admin");
        System.err.println("--- persisting employee ---");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        em.persist(employee);
        em.getTransaction().commit();
        em.close();
        System.err.println("--- employee persisted ---");
        return employee;
    }

    private static void loadEntity(EntityManagerFactory emf){
        System.err.println("--- loading employee by id ---");
        EntityManager em = emf.createEntityManager();
        System.err.println("--- calling getReference(). ---");
        Employee employee = em.getReference(Employee.class,1);
        System.err.println("--- getReference() already called ---");
        System.err.println("loaded employee name: " + employee.getName());
        em.close();
    }
}
